#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""_summary_

    Raises:
        WebApiError: _description_

    Returns:
        _type_: _description_
    """

#
# File Name:
# @Author:  paddy
# @Email:   3988263@qq.com
# @Time:    ${DATE} ${TIME}
# Project: ${PROJECT_NAME}
# ---------------------说明--------------------------
#
# ---------------------------------------------------

import logging

import json
from urllib.parse import urljoin
import requests

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(console)


class WebApi:
    """_summary_

    Raises:
        WebApiError: _description_

    Returns:
        _type_: _description_
    """
    # access_token=''
    def __init__(self, api_url, username, password):
        self.api_url = api_url
        self.username = username
        self.password = password
        self.get_access_token()

    def get_access_token(self):
        """_summary_
        """
        path = '/api/auth/login'
        url = urljoin(self.api_url, path)
        params = {
            'email': self.username,
            'password': self.password
        }
        respone = requests.post(url, data=json.dumps(params), timeout=120)
        result = respone.json()
        respone.close()
        self.access_token = result["data"]['access_token']

    def _post(self, path: str, data: str):
        """
        :param path: 路径
        :param data: post 请求参数,要求为Json字符串
        :return: status_code, message 如果报错返回 -1, 错误信息
        """
        try:
            headers = {
                "User-Agent": "User-Agent: Apifox/1.0.0 (https://apifox.com)",
                "Authorization": "Bearer "+self.access_token,
                "Content-Type": "application/json"
            }
            url = urljoin(self.api_url, path)
            _data = json.dumps(data)
            respone = requests.post(url, _data, headers=headers,  timeout=120)
            status_code = respone.status_code
            respone.close()
            if status_code != 200:
                raise ValueError('status_code=', status_code)
            message = respone.json()
            return status_code, message
        except EOFError as error:
            return -1, error

    # 添加产品
    def api_tp_product_add(self, data: str):
        """_summary_

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/tp_product/add'
        return self._post(path, data)

    #  删除产品
    def api_tp_product_delete(self, data: str):
        """_summary_

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/tp_product/delete'
        return self._post(path, data)

    # 业务添加
    def api_business_add(self, data: str):
        """_summary_

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/business/add'
        return self._post(path, data)

    # 业务删除
    def api_business_delete(self, data: str):
        """_summary_

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/business/delete'
        return self._post(path, data)

    # 业务修改
    def api_business_edit(self, data: str):
        """_summary_

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/business/edit'
        return self._post(path, data)

    # 删除分组
    def api_asset_delete(self, data: str):
        """_summary_

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/asset/delete'
        return self._post(path, data)

    # 添加设备分组
    def api_asset_add_only(self, data: str):
        """_summary_

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/asset/add_only'
        return self._post(path, data)

    # 更新设备分组
    def api_asset_add_update_only(self, data: str):
        """_summary_

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/asset/update_only'
        return self._post(path, data)

    # 查询业务下分组（包含子分组）下拉
    def api_asset_list_d(self, data: str):
        """_summary_

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/asset/list/d'
        return self._post(path, data)

    # 更新设备分组
    def api_asset_list_a(self, data: str):
        """_summary_

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/asset/list/a'
        return self._post(path, data)

    # 分页查询业务下分组id父分组名称（包含子分组）列表
    def api_asset_list_c(self, data: str):
        """_summary_

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/asset/list/c'
        return self._post(path, data)

    def api_device_add_only(self, data: str):
        """添加设备

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/device/add_only'
        return self._post(path, data)

    def edit_device_token(self, data: str):
        """设备token修改

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/device/edit'
        return self._post(path, data)

    def api_device_list_tree(self, data: str):
        """设备分页条件查询（包含网关设备树）

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/device/list/tree'
        return self._post(path, data)

    def api_business_index(self, data: str):
        """业务列表

        Args:
            data (str): _description_
        """
        path = '/api/business/index'
        return self._post(path, data)

    def api_device_list(self, data: str):
        """设备分页条件查询（xcx）不确定是否废弃

        Args:
            data (str): _description_

        Returns:
            _type_: _description_
        """
        path = '/api/device/list'
        return self._post(path, data)
